from models.base import LoginUser,RegisterUser,User,ModbusData
from fastapi import FastAPI,Depends,HTTPException,Request,Response
from connect.database import get_db,engine
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session
from pydantic import BaseModel


app = FastAPI()

templates = Jinja2Templates(directory="web")


#登录验证
@app.post("/login",status_code=200)
async def login(user: LoginUser,db: Session = Depends(get_db)):
    db_user = db.query(User).filter(User.username == user.username).first()
    if db_user and db_user.user_password == user.password:
        return {"message": "Login successful"}
    else:
        raise HTTPException(status_code=400, detail="Invalid credentials")

#注册
@app.post("/register",status_code=200)
async def register(user: RegisterUser,db: Session = Depends(get_db),):
    #检查数据库用户是否存在
    db_user = db.query(User).filter(User.username == user.username).first()
    if db_user:
        raise HTTPException(status_code=400, detail="用户已经存在")

    #创建新用户
    new_user = User(username=user.username, user_password=user.password,pergrade=user.pergrade )
    db.add(new_user)
    db.commit()
    db.refresh(new_user)

    return {"message": "用户创建成功"}


#登录界面
@app.get("/",response_class=HTMLResponse,status_code=200)
async def root(request: Request):
    return templates.TemplateResponse("login.html", {"request": request})
#注册页面
@app.get("/register",response_class=HTMLResponse,status_code=200)
async def root(request: Request):
    return templates.TemplateResponse("register.html", {"request": request})

#首页
@app.get("/index",response_class=HTMLResponse,status_code=200)
async def index(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

#创建一个新的API端点接受Modbus数据
@app.post("/modbus/data", status_code=200)
async def modbus_data(data: ModbusData, db: Session = Depends(get_db)):
    # 处理接收到的Modbus数据
    # 例如，存储到数据库中
    # ...
    return {"message": "Data received successfully"}


if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8001)